package com.bestcem.xm.member.service.impl;

import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.member.dao.MemberDao;
import com.bestcem.xm.member.entity.pojo.MemberDO;
import com.bestcem.xm.member.grpc.service.param.member.ListOrgMembersParams;
import com.bestcem.xm.member.service.TicketMemberService;
import com.bestcem.xm.member.service.dto.MemberDTO;
import com.bestcem.xm.member.service.dto.PageDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dc.wang <dc.wang@idiaoyan.com>
 * @version V1.0
 * @description 为工单单独提供的Service实现类
 * @date 2021/9/10
 */
@Component
public class TicketMemberMemberServiceImpl implements TicketMemberService {
    private final MemberDao memberDao;

    @Autowired
    public TicketMemberMemberServiceImpl(MemberDao memberDao){
        this.memberDao = memberDao;
    }

    @Override
    public ServiceResult<PageDTO<MemberDTO>> listOrgMembers(ListOrgMembersParams params) {
        // 偏移量
        Integer offset = (params.getPageParam().getPage() - 1) * params.getPageParam().getSize();

        // 查询页数
        Long memberCount = memberDao.countOrgMembers(params.getOrgId(), params.getMemberTypeEnum().getIndex());
        if(memberCount <= offset){
            return ServiceResult.success(new PageDTO<>(new ArrayList<>(0), memberCount.intValue()));
        }

        List<MemberDO> members = memberDao.listOrgMembers(params.getOrgId(),params.getMemberTypeEnum().getIndex(), offset, params.getPageParam().getSize());

        // 数据转化
        List<MemberDTO> datas = members.stream().map(this::convert).collect(Collectors.toList());
        return ServiceResult.success(new PageDTO<>(datas, memberCount.intValue()));
    }

    private MemberDTO convert(MemberDO member){
        MemberDTO res = new MemberDTO();
        if(member == null){
            return res;
        }

        res.setId(member.getId());
        res.setName(member.getName());
        res.setMobile(member.getPhone());
        res.setEmail(member.getEmail());
        return res;
    }
}
